package excel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public abstract class OperatorExcel {

	/**
	 * 写入Excel
	 * 
	 * @param header
	 *            标题
	 * @param fieldTitle
	 *            列名称
	 * @param notes
	 *            列表数据
	 * @param fildLength
	 *            列长度
	 * @param url
	 *            输出路径
	 */
	public void writeToExcel(String header, String[] fieldTitle, List notes,
			int[] fieldLength, String url) throws Exception {

		InputStream input = null;

		FormatFactory factory = new FormatFactory();

		String sheetTitle = "Sheet1";
		int sheetIndex = 0;
		OutputStream out = new FileOutputStream(url);
		// 如果传入的内容为空则返回
		if (notes == null) {
			return;
		} else if (notes.size() == 0) {
			return;
		}
		// 创建工作薄
		WritableWorkbook writbook = null;
		try {
			writbook = Workbook.createWorkbook(out);
		} catch (IOException e) {
			System.out.println("在创建工作薄时抛出异常，内容如下：");
			e.printStackTrace();
		}
		// 创建工作表并指定名称和索引位置
		WritableSheet sheet = writbook.createSheet(sheetTitle, sheetIndex);
		// 设置列的宽度
		if (fieldLength != null) {
			for (int i = 0; i < fieldLength.length; i++) {
				sheet.setColumnView(i, fieldLength[i]);
			}
		}
		// 设置合并单元格
		try {
			sheet.mergeCells(0, 0, fieldTitle.length - 1, 0);
			sheet.mergeCells(0, 1, fieldTitle.length - 1, 1);
		} catch (WriteException e) {
			System.out.println("在合并单元格时抛出异常，内容如下：");
			e.printStackTrace();
		}
		// 一些临时变量，用于写到excel中
		Label lable = null;
		// 填写工作表
		try {
			// 填写表名
			lable = new Label(0, 0, "农村商业短信平台系统", factory.getFormat(0));
			sheet.addCell(lable);
			lable = new Label(0, 1, header, factory.getFormat(0));
			sheet.addCell(lable);
			// 填写字段名
			for (int i = 0; i < fieldTitle.length; i++) {
				lable = new Label(i, 2, fieldTitle[i], factory.getFormat(1));
				sheet.addCell(lable);
			}
			// 把字段信息写入sheet内
			setSheet(sheet, notes);
			// 写入文件
			writbook.write();

			// 关闭工作薄对象，释放内存空间
			writbook.close();
		} catch (Exception e) {
			System.out.println("在填写工作表内容时抛出异常，内容如下：");
			e.printStackTrace();
		}

	}

	public abstract void setSheet(WritableSheet sheet, List notes)
			throws Exception;

}
